package com.xll.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.xll.entity.SysUser;
import com.xll.entity.WeixinRun;
import com.xll.service.SportService;
import com.xll.service.SysUserService;
import com.xll.utils.DateUtils;
import com.xll.utils.Result;
import com.xll.utils.StringUtils;
import com.xll.utils.WechatDecryptDataUtil;
import com.xll.vo.WeRun;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.swing.text.html.parser.Entity;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Api(tags = "小程序接口")
@RestController
@RequestMapping("/mini")
public class WeixinController {



    @Value("${mini.appid}")
    private  String appid;
    @Value("${mini.secret}")
    private  String secret;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SportService sportService;
    @ApiOperation(value = "微信小程序登录")
    @GetMapping("/login")
    public Result login(String code) throws IOException {
        if (StringUtils.isNEmpty(code)){
           return  Result.fail("登录失败");
        }
        //创建一个client 请求
        CloseableHttpClient build = HttpClientBuilder.create().build();
        String url = "https://api.weixin.qq.com/sns/jscode2session?"+
       "appid="+appid+ "&secret="+secret+"&js_code="+ code+ "&grant_type=authorization_code";

        //构建get请求
        HttpGet get = new HttpGet(url);
        //发送请求
        final CloseableHttpResponse response = build.execute(get);
        log.info("请求响应码",response.getStatusLine().getStatusCode());
        String result = EntityUtils.toString(response.getEntity());
        log.info("请求响应结果",result);
        JSONObject jsonObject = JSON.parseObject(result);
        String openid = jsonObject.getString("openid");
        String sessionKey = jsonObject.getString("session_key");
        log.info("微信小程序唯一标识",openid);
        Result res = sysUserService.miniLogin(openid,sessionKey);
        return  sysUserService.miniLogin(openid,sessionKey);
    }

    @ApiOperation(value = "更新用户信息")
    @PostMapping("/update/info")
    public  Result updateInfo(@RequestBody SysUser user){
       return    sysUserService.updateByOpenId(user);
    }


    @PostMapping("/werun")
    public  Result  getRunStep(@RequestBody WeRun weRun){
        String data = WechatDecryptDataUtil.decryptData(weRun.getEncryptedData(), weRun.getSessionKey(), weRun.getIv());
        log.info(data);
        JSONObject result = JSONObject.parseObject(data);
        JSONArray stepInfoList = result.getJSONArray("stepInfoList");
        List<WeixinRun> weixinRunList=new ArrayList<>();
        sportService.deleteByOpenid(weRun.getOpenid());
        for(Object object:stepInfoList){
            JSONObject obj= (JSONObject) object;
            Long timestamp = obj.getLong("timestamp");

            log.info("时间:{}", DateUtils.timestampConvertString(timestamp),obj.getInteger("step"));
            WeixinRun weixinRun = new WeixinRun();
            weixinRun.setOpenid(weRun.getOpenid());
            weixinRun.setTime(DateUtils.timestampConvertString(timestamp));
            weixinRun.setStep(obj.getInteger("step"));
            weixinRunList.add(weixinRun);
        }
        sportService.insertStep(weixinRunList);
        return  Result.success(data,weixinRunList.get(weixinRunList.size()-1).getStep());
    }

    @GetMapping("/step/statistics")
    public Result stepStatistics() throws ParseException {
         return  sportService.stepReport();
    }
}
